#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("usage:./client ip port\n");
        printf("example:./client 119.29.219.158 8080\n\n");
        return -1;
    }

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        printf("socket() failed.\n");
        return -1;
    }

    struct sockaddr_in clientaddr;
    memset(&clientaddr, 0,sizeof(clientaddr));
    clientaddr.sin_family = AF_INET;
    clientaddr.sin_addr.s_addr = inet_addr(argv[1]);
    clientaddr.sin_port = htons(atoi(argv[2]));

    int connect1 = connect(sockfd, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
    if (connect1 < 0)
    {
        printf("connect(%s:%s) failed.\n", argv[1], argv[2]);
        close(sockfd);
        return -1;
    }
    printf("connect ok\n");

    char buffer[1024];
    for (int ii = 0; ii < 200000; ii++)
    {
        memset(buffer, 0, sizeof(buffer));
        printf("please input:");
        scanf("%s", buffer);
        int n = send(sockfd, buffer, sizeof(buffer), 0);

        if (n <= 0)
        {
            printf("write() failed.\n");
            close(sockfd);
            return -1;
        }

        memset(buffer, 0, sizeof(buffer));
        if (recv(sockfd, buffer, sizeof(buffer), 0) <= 0) // 接收服务端的回应。
        {
            printf("read() failed.\n");
            close(sockfd);
            return -1;
        }
        printf("recv:%s\n", buffer);
    }
}